package org.ethereum.net.dpos;

import java.math.BigInteger;

import org.ethereum.net.rlpx.Node;
import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.util.encoders.Hex;

public class PackageRequest extends DPOSMessage {

	private final Node presidentNode;
	
	private final long round;
	
	private final byte[] presidentId;
	
	private final byte[] electionId;
	
	public PackageRequest(final byte[] encoded) {
		super(encoded);
		RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
		this.round = new BigInteger(1, paramsList.get(0).getRLPData()).longValue();
		if (round < 1) {
	    		throw new IllegalArgumentException("round must be greater then from 1!");
	    }
        this.presidentId = paramsList.get(1).getRLPData();
        this.electionId = paramsList.get(2).getRLPData();
        this.presidentNode = null;
	}
	
	public PackageRequest(final long round, final Node presidentNode, byte[] electionId) {
        super(null);
        if (round < 1) {
        		throw new IllegalArgumentException("round must be greater then from 1!");
        }
        this.round = round;
        this.presidentNode = presidentNode;
        this.presidentId = presidentNode.getId();
        this.electionId = electionId;
        
        encode();
    }
	
	private void encode() {
		 byte[] round = RLP.encodeBigInteger(BigInteger.valueOf(this.round));
	     byte[] presidentId  = RLP.encodeElement(this.presidentId);
	     byte[] electionId  = RLP.encodeElement(this.electionId);
	     this.encoded = RLP.encodeList(round, presidentId, electionId);
	}
	
	public Node getPresidentNodeInfo() {
		return presidentNode;
	}
	
	public long getRound() {
		return round;
	}

	public byte[] getPresidentId() {
		return presidentId;
	}
	
	public byte[] getElectionId() {
		return electionId;
	}

	@Override
	public DPOSMessageCodes getCommand() {
		return DPOSMessageCodes.PACKAGE_REQUEST;
	}

	@Override
	public byte[] getEncoded() {
		return this.encoded;
	}

	@Override
	public Class<?> getAnswerMessage() {
		return PackageResponse.class;
	}

	@Override
	public String toString() {
		return "{round: "+round+", presidentId: "+Hex.toHexString(presidentId)+", electionId: "+ Hex.toHexString(electionId) +" }";
	}

}
